import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { loadEnv } from 'vite'
import autoprefixer from 'autoprefixer'
import cssnano from 'cssnano'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
    const env = loadEnv(mode, process.cwd())

    return {
        plugins: [vue()],

        resolve: {
            alias: {
                '@': resolve(__dirname, 'src'),
                '@components': resolve(__dirname, 'src/components'),
                '@views': resolve(__dirname, 'src/views'),
                '@utils': resolve(__dirname, 'src/utils'),
                '@assets': resolve(__dirname, 'src/assets'),
                '@styles': resolve(__dirname, 'src/styles'),
                '@api': resolve(__dirname, 'src/api'),
                '@modules': resolve(__dirname, 'src/modules'),
                '@config': resolve(__dirname, 'src/config')
            }
        },

        css: {
            preprocessorOptions: {
                scss: {
                    // 移除可能导致循环引用的 additionalData
                    // additionalData: `@use "@/styles/variables.scss" as *; @use "@/styles/mixins.scss" as *; @use "@/styles/common.scss" as *;`
                }
            },
            // 启用CSS代码分割
            postcss: {
                plugins: [
                    autoprefixer(),
                    cssnano({
                        preset: ['default', {
                            discardComments: { removeAll: true },
                            normalizeWhitespace: false
                        }]
                    })
                ]
            }
        },

        server: {
            port: 8081,
            host: '0.0.0.0',
            open: true,
            cors: true,
            // 添加热更新优化
            hmr: {
                overlay: false
            },
            proxy: {
                '/api': {
                    target: env.VITE_API_BASE_URL || 'http://192.168.1.16:10001/',
                    changeOrigin: true,
                    rewrite: (path) => path.replace(/^\/api/, ''),
                    // 添加代理超时配置
                    timeout: 10000
                }
            }
        },

        build: {
            outDir: 'dist',
            sourcemap: mode === 'development',
            minify: 'terser',
            terserOptions: {
                compress: {
                    drop_console: mode === 'production',
                    drop_debugger: mode === 'production',
                    pure_funcs: mode === 'production' ? ['console.log'] : []
                }
            },
            rollupOptions: {
                output: {
                    // 代码分割策略
                    manualChunks: {
                        'vue-vendor': ['vue', 'vue-router', 'pinia'],
                        'chart-vendor': ['echarts', 'vue-echarts'],
                        'ui-vendor': ['element-plus', '@element-plus/icons-vue'],
                        'utils-vendor': ['axios', 'lodash-es', 'dayjs'],
                        'swiper-vendor': ['swiper', 'vue-awesome-swiper']
                    },
                    chunkFileNames: 'js/[name]-[hash].js',
                    entryFileNames: 'js/[name]-[hash].js',
                    assetFileNames: (assetInfo) => {
                        const info = assetInfo.name.split('.')
                        const ext = info[info.length - 1]
                        if (/\.(png|jpe?g|gif|svg|ico|webp)(\?.*)?$/i.test(assetInfo.name)) {
                            return `img/[name]-[hash].[ext]`
                        }
                        if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(assetInfo.name)) {
                            return `fonts/[name]-[hash].[ext]`
                        }
                        return `${ext}/[name]-[hash].[ext]`
                    }
                }
            },
            chunkSizeWarningLimit: 1000,
            // 添加构建报告
            reportCompressedSize: true,
            // 启用CSS代码分割
            cssCodeSplit: true
        },

        // 依赖预构建优化
        optimizeDeps: {
            include: [
                'vue',
                'vue-router',
                'pinia',
                'echarts',
                'vue-echarts',
                'element-plus',
                'axios',
                'lodash-es',
                'dayjs'
            ],
            exclude: ['vue-demi']
        },

        // 添加性能优化
        esbuild: {
            drop: mode === 'production' ? ['console', 'debugger'] : []
        }
    }
})
